# -*- coding:utf-8 -*-
# from baike_spider import url_manager
# from baike_spider import html_outputer
from baike_spider import html_downloader
from baike_spider import html_parser
from baike_spider import redis_url_manager
from baike_spider import mysql_outputer

class SpiderMain(object):
    def __init__(self):
        # self.urls = url_manager.UrlManager()
        # self.outputer = html_outputer.HtmlOutputer()
        self.downloader = html_downloader.HtmlDownloader()
        self.parser = html_parser.HtmlParser()
        self.outputer = mysql_outputer.DBOutputer()
        self.redisManager = redis_url_manager.RedisManager()
    def craw(self, root_url):
        count = 1
        self.redisManager.add_new_url(root_url)
        while self.redisManager.has_new_url():
            new_url = self.redisManager.get_new_url()
            try:

                print("craw %d : %s" %(count, new_url))
                html_cont = self.downloader.download(new_url)
                self.redisManager.finish_url(new_url)
                new_urls, new_data = self.parser.paser(new_url, html_cont)
                self.redisManager.add_new_urls(new_urls)
                # self.outputer.collect_data(new_data)
                self.outputer.collect_data(new_data)
                if count == 1000:
                    break
                count = count + 1
            except:
                self.redisManager.del_url(new_url)
                print('craw failed and del :'+new_url)
        # self.outputer.output_html()
        self.outputer.output_mysql()


if __name__ == '__main__':
    root_url = "https://movie.douban.com/subject/10546665/?from=subject-page"
    obj_spider = SpiderMain()
    obj_spider.craw(root_url)
